#include <cstdlib>
#include <iostream>
#include <string>
#include <set>
#include <vector>

#include "../../projectevent.h"
#include "../../projecteventbus.h"
#include "../../project_p.h"

#include "makefileprojectcompiler.h"

INIT_PROJECT_COMPILER_PLUGIN_FACTORY( MakefileProjectCompiler )
INIT_PROJECT_COMPILER_PLUGIN_NAME( "Makefile Project Compiler Plugin" )
INIT_PROJECT_COMPILER_PLUGIN_VERSION( -1 )
INIT_PROJECT_COMPILER_PLUGIN_AUTHOR( "The Cine Developer" )

void MakefileProjectCompiler::RegisterEvent( ProjectEventBus* eventBus )
{
    eventBus->AttachListener( Events::ProjectBuild, this );
    eventBus->AttachListener( Events::ProjectClean, this );
//     eventBus->AttachListener( EventType_ProjectInstall, this );//TODO
    eventBus->AttachListener( Events::ProjectRebuild, this );
}

bool MakefileProjectCompiler::HandleEvent( Events::Event* event )
{
    /// NOTE: initialize shared d-pointer here
    switch ( event->GetType() ) {
        /// import/export
        case Events::ProjectBuild: {
            d = ((ProjectBuildEvent*)(event))->d;
            build();
            break;
        }
        case Events::ProjectClean: {
            d = ((ProjectCleanEvent*)(event))->d;
            clean();
            break;
        }
        case Events::ProjectRebuild: {
            d = ((ProjectRebuildEvent*)(event))->d;
            rebuild();
            break;
        }
        default:
            std::cerr << "Unexpected Event Here!" << std::endl;
    }
    std::cerr << "catch event from makefile compiler sub plugin" << std::endl;
    return false;
}

bool MakefileProjectCompiler::build()
{
    std::string cmd = "make";
    std::cerr << cmd << std::endl;
//     system( cmd.c_str() );
    return true;
}

bool MakefileProjectCompiler::clean()
{
    std::string cmd = "make clean";
    std::cerr << cmd << std::endl;
//     system( cmd.c_str() );
    return true;
}

bool MakefileProjectCompiler::rebuild()
{
    return clean() && build();
}
